package com.hddf.project.auth.actions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kommii.common_utils.DateTime_Utils;
import org.kommii.encryption.AESHandler;
import org.kommii.log.LogNames;

import com.hddf.project.auth.json_util.JsonProvider;
import com.hddf.project.auth.pojos.User;
import com.hddf.project.auth.service.AESKeyService;
import com.hddf.project.auth.service.CookieService;
import com.hddf.project.auth.service.MongoDB_Query;
import com.hddf.project.auth.service.MongoDB_Sync;
import com.hddf.project.auth.service.RegisterService;
import com.hddf.project.auth.service.WebLoginService;
import com.mongodb.DBObject;


public class LoginAction extends BaseAction{
	
	private static final long serialVersionUID = 157657546435L;
	private String user_no;
	private String username;
	private String password ;
	private String department;
	private String description;
    private String mobile_phone;
	private int isopen  ;
	private String permission; 
	private String value;
	
	@SuppressWarnings("finally")
	public String weblogin(){
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		String state = "";
		String msg = "";
		String t = "";
		try {
			WebLoginService wls = WebLoginService.getInstance();
			RegisterService rs = RegisterService.getInstance();
			CookieService cs = CookieService.getInstance();
			AESKeyService aks = AESKeyService.getInstance();
			MongoDB_Query mq = MongoDB_Query.getInstance();
			MongoDB_Sync ms = MongoDB_Sync.getInstance();
			String decr_str = "";
			String aes_key = "";
			if(null!=value && !"".equals(value.trim())){
				Cookie cookie = cs.getCookieByName(request, "y");
				if(null!=cookie){
					String temp = cookie.getValue();
					String id = temp.split(" ")[0];
					DBObject obj = aks.getAESKeyById(id);
					if(null==obj){
						state = "timeout";
						msg = "密钥过期请重新登陆";
					}else{
						aes_key = (String)obj.get("aes_key");
						value = value.replace(" ", "+");
						long deadline = (Long)obj.get("aeskey_deadline");
						long current = DateTime_Utils.getCurrentSeconds();
						if((deadline-current)>0){
							decr_str = AESHandler.decrypt(aes_key, value);
							String[] arr = decr_str.split(" ");
							if(arr.length==2){
								username = arr[0];
								password = arr[1];
							}
							User u = mq.getUserByName(username);
							if(null==u){
								u = rs.getUserByName(username);
								if(null!=u){
									ms.addUser(u);
								}
							}
							if(null==u){
								state = "error";
								msg = username+" 用户名不存在,请检查用户名!";
							}else{
								if(u.getIsopen()==0){
									state = "error";
									msg = username+" 用户已经被管理员锁定,暂时不能进入系统";
								}else{
									msg = wls.login(username, password,aes_key);
									if("fail".equals(msg) || "exception".equals(msg)){
										state = "error";
										msg = "密码不匹配,请核实密码";
									}else{
										state = "ok";
										t = msg;
										msg = "";
									}
								}
							}						
						}else{
							state = "timeout";
							msg = "密钥过期请重新登陆";
						}
					}
				}else{
					state = "timeout";
					msg = "密钥过期请重新登陆";
				}
			}else{
				state = "error";
				msg = "请填写用户名和密码";
			}
			map.put("state", state);
			map.put("msg", msg);
			map.put("t", t);
			request.setAttribute("result", JsonProvider.getCommonJson(map));
			request.setAttribute("logname",LogNames.login);
			request.setAttribute("logs","login state : "+state+" ,login msg : "+msg+
					" , user name:"+username);
			return "simpleResult";
		} catch (Exception e) {
			e.printStackTrace();
			state = "error";
			map.put("state", state);
			map.put("msg", msg);
			request.setAttribute("result", JsonProvider.getCommonJson(map));
			return "simpleResult";
		} 
	}
	
	
	/**
	 * 获取AES 加密所需的 key
	 * @return
	 */
	public String getKey(){
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
		Map<String,Object> m = new HashMap<String,Object>();
		AESKeyService aks = AESKeyService.getInstance();
		CookieService cs = CookieService.getInstance();
		Cookie c = cs.getCookieByName(request, "y");
		if(null!=c){
			String v = c.getValue();
			if("".equals(v)){
				String str = aks.addAESKey();
				String[] arr = str.split(" ");
				String _id = arr[0];
				String aeskey = arr[1];
				cs.addCookie(response, "y", _id+" "+aeskey, 0);
			}else{
				String[] array = v.split(" ");
				v = array[0];
				DBObject obj = aks.getAESKeyById(v);
				if(null==obj){
					String str = aks.addAESKey();
					String[] arr = str.split(" ");
					String _id = arr[0];
					String aeskey = arr[1];
					cs.addCookie(response, "y", _id+" "+aeskey, 0);
				}else{
					//String aes_key = (String)obj.get("aes_key");
					long deadline = (Long)obj.get("aeskey_deadline");
					long current = DateTime_Utils.getCurrentSeconds();
					//int validTime = aks.getAESKey_validTime();
					if((deadline-current)>0){
						
					}else{
						String str = aks.addAESKey();
						String[] arr = str.split(" ");
						String _id = arr[0];
						String aeskey = arr[1];
						cs.addCookie(response, "y", _id+" "+aeskey, 0);
						aks.deleteAESKey(v);
					}
				}
			}
		}else{
			String str = aks.addAESKey();
			String[] arr = str.split(" ");
			String _id = arr[0];
			String aeskey = arr[1];
			cs.addCookie(response, "y", _id+" "+aeskey, 0);
		}
		m.put("state", "ok");
		request.setAttribute("result", JsonProvider.getCommonJson(m));
		return "simpleResult";
	}
	

	public String getUser_no() {
		return user_no;
	}


	public void setUser_no(String user_no) {
		this.user_no = user_no;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public String getDepartment() {
		return department;
	}


	public void setDepartment(String department) {
		this.department = department;
	}


	public String getDescription() {
		return description;
	}


	public void setDescription(String description) {
		this.description = description;
	}


	public String getMobile_phone() {
		return mobile_phone;
	}


	public void setMobile_phone(String mobile_phone) {
		this.mobile_phone = mobile_phone;
	}


	public int getIsopen() {
		return isopen;
	}


	public void setIsopen(int isopen) {
		this.isopen = isopen;
	}


	public String getPermission() {
		return permission;
	}


	public void setPermission(String permission) {
		this.permission = permission;
	}


	public String getValue() {
		return value;
	}


	public void setValue(String value) {
		this.value = value;
	}

	

}
